// 异常订单处理模块
class OrderException {
    constructor() {
        this.exceptionTypes = {
            delivery: '配送异常',
            payment: '支付异常',
            quality: '质量问题'
        };
        
        this.statusTypes = {
            pending: '待处理',
            processing: '处理中',
            resolved: '已解决'
        };
        
        this.init();
    }
    
    init() {
        this.showOrderExceptionContent();
        this.renderExceptionList();
        this.bindEvents();
        this.startAutoRefresh();
    }

    showOrderExceptionContent() {
        // 确保必要的DOM结构存在
        let contentWrapper = document.querySelector('.content-wrapper');
        if (!contentWrapper) {
            contentWrapper = document.createElement('div');
            contentWrapper.className = 'content-wrapper';
            document.body.appendChild(contentWrapper);
        }

        // 创建或获取store-monitor元素
        let storeMonitor = document.querySelector('.store-monitor');
        if (!storeMonitor) {
            storeMonitor = document.createElement('div');
            storeMonitor.className = 'store-monitor';
            contentWrapper.appendChild(storeMonitor);
        }

        // 创建或获取order-exception元素
        let orderException = document.querySelector('.order-exception');
        if (!orderException) {
            orderException = document.createElement('div');
            orderException.className = 'order-exception';
            contentWrapper.appendChild(orderException);
        }

        // 隐藏其他内容
        storeMonitor.style.display = 'none';
        // 显示异常订单内容
        orderException.style.display = 'block';
    }
    
    // 获取异常订单列表
    async fetchExceptionOrders() {
        // 模拟异步获取数据
        return new Promise(resolve => {
            setTimeout(() => {
                resolve([
                    {
                        id: 'DD20230001',
                        type: 'delivery',
                        status: 'pending',
                        createTime: '2023-12-20 14:30:00',
                        description: '骑手未按时取餐',
                        priority: 'high',
                        progress: [
                            {
                                time: '2023-12-20 14:30:00',
                                content: '系统自动识别为配送异常订单'
                            }
                        ]
                    },
                    {
                        id: 'DD20230002',
                        type: 'payment',
                        status: 'processing',
                        createTime: '2023-12-20 14:25:00',
                        description: '用户支付失败',
                        priority: 'medium',
                        progress: [
                            {
                                time: '2023-12-20 14:25:00',
                                content: '系统自动识别为支付异常订单'
                            },
                            {
                                time: '2023-12-20 14:28:00',
                                content: '客服已介入处理'
                            }
                        ]
                    }
                ]);
            }, 500);
        });
    }
    
    // 渲染异常订单列表
    async renderExceptionList() {
        const orders = await this.fetchExceptionOrders();
        const container = document.querySelector('.content-wrapper .exception-list');
        
        // 如果容器不存在，先创建它
        if (!container) {
            const contentWrapper = document.querySelector('.content-wrapper');
            if (contentWrapper) {
                contentWrapper.innerHTML = '<div class="exception-list"></div>';
            }
            return;
        }
        
        if (!orders.length) {
            container.innerHTML = this.renderEmptyState();
            return;
        }
        
        container.innerHTML = orders.map(order => this.renderOrderItem(order)).join('');
    }
    
    // 渲染单个订单项
    renderOrderItem(order) {
        return `
            <div class="exception-item" data-id="${order.id}">
                <div class="order-info">
                    <div class="order-id">${order.id}</div>
                    <span class="exception-type type-${order.type}">
                        ${this.exceptionTypes[order.type]}
                    </span>
                    <span class="status-tag status-${order.status}">
                        ${this.statusTypes[order.status]}
                    </span>
                    <div class="progress-tracker">
                        ${this.renderProgress(order.progress)}
                    </div>
                </div>
                <div class="action-buttons">
                    ${this.renderActionButtons(order)}
                </div>
            </div>
        `;
    }
    
    // 渲染进度追踪
    renderProgress(progress) {
        return progress.map(step => `
            <div class="progress-step">
                <span class="step-time">${step.time}</span>
                <div class="step-content">${step.content}</div>
            </div>
        `).join('');
    }
    
    // 渲染操作按钮
    renderActionButtons(order) {
        if (order.status === 'resolved') {
            return `
                <button class="action-button button-default" onclick="orderException.viewDetail('${order.id}')">
                    查看详情
                </button>
            `;
        }
        
        return `
            <button class="action-button button-primary" onclick="orderException.handleException('${order.id}')">
                ${order.status === 'pending' ? '立即处理' : '继续处理'}
            </button>
            <button class="action-button button-default" onclick="orderException.viewDetail('${order.id}')">
                查看详情
            </button>
        `;
    }
    
    // 渲染空状态
    renderEmptyState() {
        return `
            <div class="empty-state">
                <div class="empty-state-icon">📋</div>
                <div>暂无异常订单</div>
            </div>
        `;
    }
    
    // 处理异常订单
    async handleException(orderId) {
        // 模拟处理流程
        const order = await this.getOrderDetail(orderId);
        if (!order) return;
        
        // 根据异常类型调用不同的处理流程
        switch (order.type) {
            case 'delivery':
                await this.handleDeliveryException(order);
                break;
            case 'payment':
                await this.handlePaymentException(order);
                break;
            case 'quality':
                await this.handleQualityException(order);
                break;
        }
        
        // 刷新列表
        this.renderExceptionList();
    }
    
    // 查看订单详情
    async viewDetail(orderId) {
        const order = await this.getOrderDetail(orderId);
        if (!order) return;
        
        // 实现查看详情的弹窗逻辑
        console.log('查看订单详情:', order);
    }
    
    // 获取订单详情
    async getOrderDetail(orderId) {
        // 模拟获取订单详情
        return new Promise(resolve => {
            setTimeout(() => {
                const orders = [
                    {
                        id: 'DD20230001',
                        type: 'delivery',
                        status: 'pending',
                        createTime: '2023-12-20 14:30:00',
                        description: '骑手未按时取餐',
                        priority: 'high',
                        progress: [
                            {
                                time: '2023-12-20 14:30:00',
                                content: '系统自动识别为配送异常订单'
                            }
                        ]
                    }
                ];
                resolve(orders.find(order => order.id === orderId));
            }, 300);
        });
    }
    
    // 处理配送异常
    async handleDeliveryException(order) {
        // 实现配送异常处理逻辑
        console.log('处理配送异常:', order);
    }
    
    // 处理支付异常
    async handlePaymentException(order) {
        // 实现支付异常处理逻辑
        console.log('处理支付异常:', order);
    }
    
    // 处理质量问题
    async handleQualityException(order) {
        // 实现质量问题处理逻辑
        console.log('处理质量问题:', order);
    }
    
    // 绑定事件
    bindEvents() {
        // 实现事件绑定逻辑
    }
    
    // 启动自动刷新
    startAutoRefresh() {
        setInterval(() => this.renderExceptionList(), 30000); // 每30秒刷新一次
    }
}

// 导出异常订单处理类
export default OrderException;